
import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import * as menuService from '../../../services/menus';
import { deepEqual } from '../../../utils/objects';
import * as compService from '../../../services/CompAccoEditInrt';
const daoName = "DgckLLwhqk";
const ButtonGroup = Button.Group;
const columns = [
  { title: '生效日期', width: 100, sorter: true, key: 'SXRQ', caption: "SXRQ", render: data => datetime.format(data.SXRQ, "yyyy-MM-dd"), dispaly: true, filter: true, },
  { title: '利率', width: 100, sorter: true, dataIndex: 'INRT', key: 'INRT', dispaly: true },
];
const controls = [
  { name: "SXRQ", required: false, type: "date", label: "生效日期", grid: 12 / 24, dataType: "date", disabled: true },
  { name: "INRT", label: "利率", type: "number", grid: 12 / 24, required: true },
]
const EditFrom = dataEditCreate(daoName);
class COMP_ACCO_INRT_WH extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      searchData: {},
      diviDataSource: [],
      title: "",
      showEdit: false,
      isOK: 0
    };
  }
  componentWillReceiveProps(nextProps) {
    if ((!deepEqual(nextProps.jlid, this.props.jlid))) {
      this.loadData(nextProps.jlid)
    }
  }
  componentDidMount() {
    this.loadData(this.props.jlid)
  }
  loadData(jlid) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
      FieldName: "ACID",
      Operator: "=",
      FieldValues: '' + jlid
    })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    let sort = {
      field: 'SXRQ',
      order: 'descend'
    }
    this.state.diviDataSource = [];
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks, sorter: sort }
    });
  }
  hideEditHandler() {
    this.props.dispatch({
      type: `${this.props.parentModel}/hideEdit`
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.setState({ diviDataSource: [] });
    this.componentDidMount()
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  diviDel() {
    let keys = this.refs.table.getSelectedRowKeys();
    keys.sort();
    const datas = this.refs.table.state.datas;
    let indexs = [];
    const keyName = 'SXRQ'
    datas.map((d, k) => {
      for (let i = 0; i < keys.length; i++) {
        if (d[keyName] === keys[i]) {
          indexs.push(k)
        }
      }
    })
    if (indexs.length <= 0) {
      message.info('请选择删除的数据行！');
      return
    }
    let diviDsource = this.state.diviDataSource;
    if (diviDsource.length <= 0) {
      diviDsource = this.props.list;
    }
    for (let j = indexs.length - 1; j >= 0; j--) {
      const k = indexs[j]
      diviDsource.splice(k, 1)
    }
    this.setState({ diviDataSource: diviDsource })
  }
  diviSubmit() {
    const datas = this.refs.table.state.datas;
    if (datas.length <= 0) {
      message.error("请添加数据！")
      return
    }
    let jlid = this.props.jlid;
    compService.Edit({ jlid, datas }
    ).then(function (data) {
      if (data) {
        message.success('保存利率成功！')
      } else {
        return;
      }
    }).catch(function (ex) {
      console.log('请求出错', ex)
    });
    let sort = {
      field: 'OPDT',
      order: 'descend'
    }
    this.props.dispatch({
      type: `${"DgckLLwh"}/setSelectedRowKeys`,
      payload: { selectedRowKeys: [] }
    });
    this.props.dispatch({
      type: `${this.props.parentModel}/reload`,
      payload: { daoName: this.props.parentModel }
    });
  };
  DiviAdd() {
    const datas = this.refs.table.state.datas;
    const form = this.refs.diviForm.getForm();
    let data = {};//空对象
    let inrt = 0
    let sxrq = ''
    let isok = true
    let diviDs = this.state.diviDataSource
    if (datas.length > 0) {
      diviDs = datas
    }
    form.validateFields((err, values) => {
      if (!err) {
        if (values["rq"] === null) {
          message.error("生效日期不能为空！")
          isok = false
          return
        }
        if (values["ll"] === undefined) {
          message.error("利率不能为空！")
          isok = false
          return
        }
      }
      inrt = Number(values["ll"])
      sxrq = values["rq"]
    });
    if (!isok) {
      return
    }
    data.SXRQ = sxrq
    data.INRT = inrt
    diviDs.push(data);
    this.setState({ diviDataSource: diviDs });
  }
  render() {
    let { list } = this.props
    list = this.state.diviDataSource.length <= 0 ? list : this.state.diviDataSource;
    const controlsFilter = [
      { name: 'rq', type: 'date', label: '生效日期', grid: 9 / 24, dataType: "date", layout: { labelSpan: 8, wrapperSpan: 13 } },
      { name: 'll', type: 'number', label: '利率(%)', grid: 7 / 24, dataType: "number", layout: { labelSpan: 11, wrapperSpan: 10 } },
      {
        name: 'XS', required: false, type: 'button-group',
        data: [{ value: '1', label: '新增', onClick: this.DiviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }],
        grid: 8 / 24, layout: { labelSpan: 7, wrapperSpan: 15 }
      },
    ];
    return (
      <Modal title={this.props.title} okText={"保存"} width={700} visible={this.props.showEdit} onCancel={this.hideEditHandler.bind(this)} onOk={this.diviSubmit.bind(this)} >
        <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
          <div>
            <div className={styles.create}>
              <EditFrom ref="diviForm" daoName={daoName} controls={controlsFilter} clearItemMargin={true} selectFirst={false} />
            </div>
            <DataEditTable ref="table" columns={columns} controls={controls} footer={true} dataSource={list} multiSelect={true} keyName={"SXRQ"} reload={true} />
          </div>
        </div>
      </Modal>
    )
  }

}

COMP_ACCO_INRT_WH.propTypes = {
  jlid: PropTypes.number,
  showEdit: PropTypes.bool,
  title: PropTypes.string,
  parentModel: PropTypes.string


};
COMP_ACCO_INRT_WH.defaultProps = {
  jlid: -1,
  showEdit: false,
  title: "",
  parentModel: ""
};

function mapStateToProps(state) {
  const { list } = state.DgckLLwhqk;
  return {
    list
  }
}
COMP_ACCO_INRT_WH = connect(mapStateToProps)(COMP_ACCO_INRT_WH)
export default COMP_ACCO_INRT_WH;
